package com.sky.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisKeyConstant;
import com.sky.entity.Admins;
import com.sky.result.Result;
import com.sky.service.AdminUserService;
import com.sky.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 管理员敏感操作验证码相关接口
 */
@RestController
@RequestMapping("/admin/verify")
@Slf4j
public class AdminVerificationController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AdminUserService adminUserService;

    /**
     * 发送封禁用户的验证码
     *
     * @param userId 目标用户id
     * @return Result
     */
    @GetMapping("/user/ban/{userId}")
    @SaCheckPermission(value = "UserManagementRelated", orRole = {"SuperAdmin", "UserAdmin"})
    public Result sendBanUserCode(@PathVariable Integer userId) {
        // 生成6位随机验证码
        String verificationCode = String.format("%06d", new Random().nextInt(1000000));
        
        // 获取当前管理员信息
        Integer adminId = StpUtil.getLoginIdAsInt();
        Admins admin = adminUserService.getAdminDetails(adminId);
        
        // 存储验证码到Redis(5分钟有效)
        String redisKey = RedisKeyConstant.ADMIN_BAN_USER_CODE + adminId + ":" + userId;
        redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
        
        // 发送验证码邮件
        emailService.sendCaptchaEmail(
            admin.getEmail(),
            admin.getUsername(),
            "封禁用户",
            verificationCode
        );
        
        return Result.success(MessageConstant.SEND_VERIFICATION_CODE_SUCCESS);
    }

    /**
     * 发送解封用户的验证码
     *
     * @param userId 目标用户id
     * @return Result
     */
    @GetMapping("/user/unban/{userId}")
    @SaCheckPermission(value = "UserManagementRelated", orRole = {"SuperAdmin", "UserAdmin"})
    public Result sendUnbanUserCode(@PathVariable Integer userId) {
        // 生成6位随机验证码
        String verificationCode = String.format("%06d", new Random().nextInt(1000000));
        
        // 获取当前管理员信息
        Integer adminId = StpUtil.getLoginIdAsInt();
        Admins admin = adminUserService.getAdminDetails(adminId);
        
        // 存储验证码到Redis(5分钟有效)
        String redisKey = RedisKeyConstant.ADMIN_UNBAN_USER_CODE + adminId + ":" + userId;
        redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
        
        // 发送验证码邮件
        emailService.sendCaptchaEmail(
            admin.getEmail(),
            admin.getUsername(),
            "解封用户",
            verificationCode
        );
        
        return Result.success(MessageConstant.SEND_VERIFICATION_CODE_SUCCESS);
    }

    /**
     * 发送删除用户的验证码
     *
     * @param userId 目标用户id
     * @return Result
     */
    @GetMapping("/user/delete/{userId}")
    @SaCheckPermission(value = "UserManagementRelated", orRole = {"SuperAdmin", "UserAdmin"})
    public Result sendDeleteUserCode(@PathVariable Integer userId) {
        // 生成6位随机验证码
        String verificationCode = String.format("%06d", new Random().nextInt(1000000));
        
        // 获取当前管理员信息
        Integer adminId = StpUtil.getLoginIdAsInt();
        Admins admin = adminUserService.getAdminDetails(adminId);
        
        // 存储验证码到Redis(5分钟有效)
        String redisKey = RedisKeyConstant.ADMIN_DELETE_USER_CODE + adminId + ":" + userId;
        redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
        
        // 发送验证码邮件
        emailService.sendCaptchaEmail(
            admin.getEmail(),
            admin.getUsername(),
            "删除用户",
            verificationCode
        );
        
        return Result.success(MessageConstant.SEND_VERIFICATION_CODE_SUCCESS);
    }

    /**
     * 发送删除管理员账户的验证码
     * 说明：
     * 1. 生成6位随机验证码
     * 2. 验证码有效期5分钟
     * 3. 验证码通过邮件发送给当前操作的管理员
     * 4. 需要超级管理员权限
     *
     * @param adminId 目标管理员ID
     * @return Result
     */
    @GetMapping("/admin/delete/{adminId}")
    @SaCheckPermission(value = "adminUser", orRole = {"SuperAdmin"})
    public Result sendDeleteAdminCode(@PathVariable Integer adminId) {
        log.info("发送删除管理员验证码，目标管理员ID：{}", adminId);
        
        // 生成6位随机验证码
        String verificationCode = String.format("%06d", new Random().nextInt(1000000));
        
        // 获取当前管理员信息
        Integer currentAdminId = StpUtil.getLoginIdAsInt();
        Admins admin = adminUserService.getAdminDetails(currentAdminId);
        
        // 存储验证码到Redis(5分钟有效)
        String redisKey = RedisKeyConstant.ADMIN_DELETE_ADMIN_CODE + currentAdminId + ":" + adminId;
        redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
        
        // 发送验证码邮件
        emailService.sendCaptchaEmail(
            admin.getEmail(),
            admin.getUsername(),
            "删除管理员账户",
            verificationCode
        );
        
        return Result.success(MessageConstant.SEND_VERIFICATION_CODE_SUCCESS);
    }

    /**
     * 发送删除角色的验证码
     * 说明：
     * 1. 生成6位随机验证码
     * 2. 验证码有效期5分钟
     * 3. 验证码通过邮件发送给当前操作的管理员
     * 4. 需要超级管理员权限
     *
     * @param roleId 目标角色ID
     * @return Result
     */
    @GetMapping("/role/delete/{roleId}")
    @SaCheckPermission(value = "roleManagement", orRole = {"SuperAdmin"})
    public Result sendDeleteRoleCode(@PathVariable Integer roleId) {
        log.info("发送删除角色验证码，目标角色ID：{}", roleId);
        
        // 生成6位随机验证码
        String verificationCode = String.format("%06d", new Random().nextInt(1000000));
        
        // 获取当前管理员信息
        Integer adminId = StpUtil.getLoginIdAsInt();
        Admins admin = adminUserService.getAdminDetails(adminId);
        
        // 存储验证码到Redis(5分钟有效)
        String redisKey = RedisKeyConstant.ADMIN_DELETE_ROLE_CODE + adminId + ":" + roleId;
        redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
        
        // 发送验证码邮件
        emailService.sendCaptchaEmail(
            admin.getEmail(),
            admin.getUsername(),
            "删除角色",
            verificationCode
        );
        
        return Result.success(MessageConstant.SEND_VERIFICATION_CODE_SUCCESS);
    }
} 